
import {User} from './screen/types'

const apiUrl = process.env.REACT_APP_API_URL;

const localStoregeKey = '__ayth_provider_token__'

export const getToken = ()=>window.localStorage.getItem(localStoregeKey)

export const handleUserResponse = ({user}:{user:User})=>{
    window.localStorage.setItem(localStoregeKey,user.token || '')
    return user
}

export const login = (data:{username:string,password:string})=>{
    fetch(`api/login`,{
        method:'POST',
        headers:{
            'Content-type':'application/json',
        },
        body:JSON.stringify(data)
    }).then(
        async (response:Response)=>{
            if(response.ok){
                return handleUserResponse(await response.json())
            }
        }
    )
}

export const register = (data:{username:string,password:string})=>{
    fetch(`${apiUrl}/regisiter`,{
        method:'POST',
        headers:{
            'Content-type':'application/json',
        },
        body:JSON.stringify(data)
    }).then(
        async (response:Response)=>{
            if(response.ok){
                return handleUserResponse(await response.json())
            }
        }
    )
}

export const logout = () => window.localStorage.removeItem(localStoregeKey)